<template>
  <!-- 回收订单  我回收的 -->
  <div class="app-container backorder_page">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="90px">
      <!-- <el-form-item label="游戏类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择游戏"  clearable @change="search">
              <el-option v-for="dict in dict.type.game_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
      <el-form-item el-form-item label="店铺" prop="buyerTenantId" v-hasPermi="['searchTenantID']">
        <el-select v-model="queryParams.buyerTenantId" placeholder="请选择店铺" clearable filterable>
          <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
        </el-select>
      </el-form-item>
      <el-form-item label-width="70px" label="部门" prop="deptIdList" v-hasPermi="['goods:list:deptSearch']">
        <el-select  clearable class="bumen" collapse-tags v-model="queryParams.deptIdList" placeholder="请选择" multiple filterable>
          <el-option v-for="dict in allDepts" :key="dict.deptId" :label="dict.deptName" :value="dict.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable>
          <el-option label="我的回收" :value="1" />
          <el-option label="竞价回收" :value="2" />
          <el-option label="自建回收单" :value="3" />
          <el-option label="C端竞价回收" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="buyerPayStatus">
        <el-select v-model="queryParams.buyerPayStatus" placeholder="请选择支付状态" clearable filterable>
          <el-option label="已支付" :value="2" />
          <el-option label="未支付" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="换绑状态" prop="changeBindState">
        <el-select v-model="queryParams.changeBindState" placeholder="请选择换绑状态" clearable filterable>
          <el-option label="已换绑" :value="2" />
          <el-option label="未换绑" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label-width="70px" label="回收人" prop="buyerIdList">
        <el-select class="bumen"  multiple collapse-tags filterable clearable v-model="queryParams.buyerIdList" placeholder="请选择回收人">
          <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="回收渠道" prop="channel">
        <!-- <el-input v-model="queryParams.channel" placeholder="请输入回收渠道名称" clearable /> -->
        <el-select filterable clearable v-model="queryParams.channel" placeholder="请选择回收渠道">
          <el-option v-for="(item ,key) in qudaoList" :key="key" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入订单编号" clearable />
      </el-form-item>
      <el-form-item label="三方单号" prop="otherNo">
        <el-input v-model="queryParams.otherNo" placeholder="请输入三方单号" clearable />
      </el-form-item>
      <el-form-item label="号主电话" prop="sellerPhone">
        <el-input v-model="queryParams.sellerPhone" placeholder="请输入号主手机" clearable />
      </el-form-item>
      <el-form-item label="游戏账号" prop="accountNumber">
        <el-input v-model="queryParams.accountNumber" placeholder="请输入游戏账号" clearable />
      </el-form-item>
      <el-form-item label="游戏名称" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="">
        <el-date-picker clearable v-model="timer" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="完成时间" prop="">
        <el-date-picker v-model="successTimer" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <!-- 
          <el-form-item label="失败时间" prop="" v-show="actived == '交易失败'">
            <el-date-picker v-model="errorTimer" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item> -->
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="search" class="zdy-btn">搜索</el-button>
        <el-button icon="el-icon-refresh" type="warning" plain @click="resetQuery">重置</el-button>

        <el-button type="primary" icon="el-icon-plus" v-if="checkPermi(['backOrder:add'])" @click="openCreate" class="zdy-btn">创建回收单</el-button>

        <el-button style="margin-left: 10px" type="warning" icon="el-icon-setting" plain @click="headerSet">表头设置</el-button>
        <el-button style="margin-left: 10px" type="success" icon="el-icon-check" plain @click="openOrderCheck">三方订单校验</el-button>
      </el-form-item>
    </el-form>
    <div class="customTab customTabNew" v-loading="loading">
      <div class="tabs flex ">
        <el-radio-group v-model="actived" @change="tabChange">
          <el-radio-button :label="i" v-for="(tab,i) in statesMap" :key="i">{{ tab.label }}</el-radio-button>
        </el-radio-group>
        <div class="tongji_box" v-if="totalNumber">
          <span>
            总应付金额:
            <span class="price">{{ formatter(totalNumber.buyerActualAmountSum||0) }}</span>元
          </span>
        </div>
      </div>
      <!-- <el-tabs type="border-card" v-model="actived" @tab-click="tabChange" v-loading="loading">
        <el-tab-pane :label="tab.label" :name="i" v-for="(tab,i) in statesMap" :key="i"> -->
      <div class="table_box table_box_new" v-if="columnList&&columnList.length">
        <el-table :data="tableData.records" border stripe height="calc(100vh - 430px)">
          <template v-for="column in columnList">
            <el-table-column :key="column.key" v-if="column.isShow" :label="column.label" :width="column.width" :min-width="column.minWidth" :prop="column.key" :sortable="column.sortable">
              <template slot-scope="scope">
                <template v-if="column.key=='orderType'">
                  <span>
                    <el-tag type="warning" v-if="scope.row.orderType==3">自建订单</el-tag>
                    <el-tag type="warning" v-if="scope.row.orderType==2">竞价回收</el-tag>
                    <el-tag type="warning" v-if="scope.row.orderType==1">我的回收</el-tag>
                    <el-tag type="warning" v-if="scope.row.orderType==4">C端竞价回收</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='orderStatus'">
                  <div>
                    <el-tag :type="commonMaps.backOrderStateMap[scope.row.orderStatus||1].type">{{commonMaps.backOrderStateMap[scope.row.orderStatus||1].label}}</el-tag>
                  </div>
                </template>
                <template v-else-if="column.key=='buyerPayStatus'">
                  <div>
                    <span style="cursor: pointer;">
                      <el-tag type="success" v-if="scope.row.buyerPayStatus==2" @click="openBillDialog(scope.row.buyerFinancialStatementId,true)">已支付</el-tag>
                      <el-tag type="danger" v-if="scope.row.buyerPayStatus==1">未支付</el-tag>
                      <el-tag type="warning" v-if="scope.row.buyerPayStatus==3" @click="openBillDialog(scope.row.buyerFinancialStatementId,true)">打款中</el-tag>
                      <el-tag type="info" v-if="scope.row.buyerPayStatus==4" @click="openBillDialog(scope.row.buyerFinancialStatementId,true)">财务拒绝</el-tag>
                    </span>
                  </div>
                </template>
                <template v-else-if="column.key=='changeBindState'">
                  <span>
                    <el-tag v-if="scope.row.changeBindState==1" :type="'danger'">未换绑</el-tag>
                    <el-tag v-if="scope.row.changeBindState==2" :type="'success'">已换绑</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='guaranteePayStatus'">
                  <span style="cursor: pointer;" @click="openBillDialog(scope.row.guaranteeFinancialStatementId,true)">
                    <el-tag type="danger" v-if="scope.row.guaranteePayStatus==1||!scope.row.guaranteePayStatus">未放款</el-tag>
                    <el-tag type="success" v-if="scope.row.guaranteePayStatus==2">已放款</el-tag>
                    <el-tag type="warning" v-if="scope.row.guaranteePayStatus==3">放款中</el-tag>
                    <el-tag type="info" v-if="scope.row.guaranteePayStatus==4">财务拒绝</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='guaranteeRefundStatus'">
                  <span style="cursor: pointer;" @click="openBillDialog(scope.row.guaranteeRefundFinancialStatementId,true)">
                    <el-tag type="danger" v-if="scope.row.guaranteeRefundStatus==1||!scope.row.guaranteeRefundStatus">未退款</el-tag>
                    <el-tag type="success" v-if="scope.row.guaranteeRefundStatus==2">已退款</el-tag>
                    <el-tag type="warning" v-if="scope.row.guaranteeRefundStatus==3">退款中</el-tag>
                    <el-tag type="info" v-if="scope.row.guaranteeRefundStatus==4">财务拒绝</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='signContractState'">
                  <span v-if="scope.row.orderType==3" style="color: #333;">
                    请在“合同管理”自行签署合同
                  </span>
                  <span v-else style="cursor: pointer;">

                    <el-tag type="danger" v-if="scope.row.signContractState==1||!scope.row.signContractState">未签署</el-tag>
                    <el-tag type="warning" v-if="scope.row.signContractState==2">签署中</el-tag>
                    <el-tag type="success" v-if="scope.row.signContractState==3">已签署</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='shouhou'">
                  <span  style="cursor: pointer;">
                    <el-tag v-if="scope.row.isAfter==2" type="warning" @click="openAfterOrder(scope.row)">处理中</el-tag>
                    <el-tag v-if="scope.row.isAfter==3" type="success" @click="openAfterOrder(scope.row)">已处理</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='shoukuanzhanghu'">

                  <span v-if="scope.row.guaranteeTenantId">{{getRowBaopeiInfo(scope.row.guaranteeTenantCollection)}}</span>
                  <span v-if="!scope.row.guaranteeTenantId&&scope.row.guaranteeInfo">{{getRowsellerBankInfo(scope.row.guaranteeInfo).collectionRemark}}</span>
                  <span v-if="scope.row.orderType==3&&scope.row.guaranteeTenantCollection">{{ getRowBaopeiInfo(scope.row.guaranteeTenantCollection) }}</span>
                </template>

                <template v-else-if="column.key=='buyerImg'||column.key=='secondImg'||column.key=='walletImg'">
                  <img-box width="50px" height="50" :img="scope.row[column.key]"></img-box>
                </template>
                <template v-else-if="column.key=='otherImg'">
                  <img-box width="50px" height="50" isWrap="nowrap" :img="scope.row[column.key]"></img-box>
                </template>
                <template v-else-if="column.key=='goodsId'">
                  <span @click="editGoods(scope.row.goodsId)" class="link">{{scope.row.goodsId||''}}</span>
                </template>
                <template v-else-if="column.key=='remark'">
                  <el-popover title="备注" trigger="hover"  placement="top-start">
                    <div class="popover-box">
                      {{ scope.row[column.key] }}
                    </div>
                    <div slot="reference"  class="zdy-des">{{ scope.row[column.key] }}</div>
                  </el-popover>
                 
                </template>

                <template v-else>
                  <span>{{scope.row[column.key]||''}}</span>
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" label="操作" min-width="260">
            <template slot-scope="scope">
              <el-button type="text" @click="openDaKuan(scope.row)" v-if="checkPermi(['backOrder:shenqingdakuan'])&&  scope.row.orderStatus == 1&&(scope.row.buyerPayStatus==1||scope.row.buyerPayStatus==4)">支付截图</el-button>
              <el-button type="text" @click="createContract(scope.row)" v-if="checkPermi(['backOrder:quanshuhetong'])&& !scope.row.guaranteeTenantId&&scope.row.signContractState==1">签署合同</el-button>
              <el-button type="text" @click="openContract(scope.row.signContractId)" v-if="scope.row.signContractId&&checkPermi(['backOrder:quanshuhetong'])&& !scope.row.guaranteeTenantId&&(scope.row.signContractState==2||scope.row.signContractState==3)">查看合同</el-button>
              <el-button type="edit" @click="gaijia(scope.row)" v-if="checkPermi(['backOrder:editOrder'])&&scope.row.orderStatus == 1">修改</el-button>
              <el-button type="del" @click="cancelOrder(scope.row)" v-if="checkPermi(['backOrder:cancelOrder'])&& scope.row.orderStatus == 1&&!scope.row.guaranteeTenantId">取消交易</el-button>
              <el-button type="add" @click="wanchenghuanbang(scope.row)" v-if="checkPermi(['backOrder:wanchenghuanbang'])&& scope.row.changeBindState == 1&&scope.row.orderStatus != 5">完成换绑</el-button>
              <el-button type="add" @click="finishOrder(scope.row)" v-if="checkPermi(['backOrder:wanchenghuanbang'])&&scope.row.orderStatus == 1&&!scope.row.guaranteeTenantId">完成交易</el-button>
              <el-button type="text" v-if="checkPermi(['backOrder:viewOrder'])" @click="openOrderDetail(scope.row)">订单详情</el-button>
              <el-button type="text" v-if="scope.row.toGroup" @click="goIM(scope.row.toGroup)">进入群聊</el-button>
              <el-button type="del" v-if="checkPermi(['backOrder:jiesanqunzu'])&& scope.row.toGroup&&!scope.row.guaranteeTenantId" @click="cancelGroupIM(scope.row.id)">解散群组</el-button>
              <el-button type="text" v-if="checkPermi(['backOrder:huifuqunzu'])&& scope.row.msgGroupInfoId&&!scope.row.toGroup&&!scope.row.guaranteeTenantId" @click="recoveryGroup(scope.row.id)">恢复群组</el-button>
              <el-button type="edit" @click="openEditBaopeiInfo(scope.row)" v-if="checkPermi(['backOrder:baopeiziliao'])&&scope.row.orderStatus == 1">包赔资料</el-button>

              <!-- &&scope.row.guaranteeTenantId -->
              <el-button type="del" @click="openShouhou(scope.row)" v-if="checkPermi(['backOrder:shenqingshouhou'])&&scope.row.orderStatus == 4&&scope.row.isAfter!=2">申请售后</el-button>
              <el-button type="text" @click="fabuNow(scope.row.id)" v-if="scope.row.orderStatus == 4&&scope.row.onState==1">立即发布</el-button>
              <!-- <el-button type="text" @click="editGoods(scope.row.goodsId)" v-if="scope.row.orderStatus == 4&&scope.row.onState==2&&scope.row.goodsId">商品详情</el-button> -->
              <!-- 自建订单可以修改和删除 -->
              <el-button v-if="scope.row.orderType==3&&scope.row.isAudit==1&&checkPermi(['backOrder:editOrder'])" type="edit" @click="editOrder(scope.row.id)">修改订单</el-button>
              <el-button v-if="scope.row.orderType==3&&scope.row.isAudit==1&&scope.row.onState!=2&&checkPermi(['backOrder:delOrder'])" type="del" @click="delOrder(scope.row.id)">删除订单</el-button>
              <el-button v-if="scope.row.orderType==3&&scope.row.isAudit==1&&checkPermi(['backOrder:editOrder'])" type="edit" @click="getBaopeiInfoLink(scope.row.id)">包赔填报链接</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
      <!-- 
        </el-tab-pane>
      </el-tabs> -->
    </div>

    <selectBaopei ref="selectBaopei" @pullBaopeiSure="pullBaopeiSure"></selectBaopei>

    <!--  2023 12 04 新增 -->
    <orderDetailDialog ref="orderDetailDialog"></orderDetailDialog>
    <editPriceDialog ref="editPriceDialog"></editPriceDialog>
    <shenQingDakuanDialog ref="shenQingDakuanDialog"></shenQingDakuanDialog>
    <baopeiEditDialog ref="baopeiEditDialog"></baopeiEditDialog>
    <shenQingShouhouDialog ref="shenQingShouhouDialog"></shenQingShouhouDialog>
    <!--发布商品 -->
    <addGoodsDialog ref="addGoodsDialog"></addGoodsDialog>
    <!-- 店铺认证弹窗 -->
    <authDialog ref="authDialog"></authDialog>
    <!-- 合同签署详情 -->
    <viewContract ref="viewContract"></viewContract>

    <!-- 创建订单弹窗 -->
    <createOrderCustom @addSuccess="getList" ref="createOrderCustom"></createOrderCustom>
    <!-- 完成订单弹窗 -->
    <finishOrderDialog ref="finishOrderDialog"></finishOrderDialog>

    <editTableHeader ref="editTableHeader" @save="headerSave"></editTableHeader>

    <!-- 创建合同弹窗 -->
    <createContract ref="createContractRef"></createContract>
    <!-- 导入号码匹配商品 -->
     <!--批量 导入弹出 -->
    <el-dialog title="批量导入" :visible.sync="showInportVisible" width="430px" append-to-body>
      <div v-loading="isUploading" element-loading-text="正在处理中，可能时间较长，请耐心等待...">
       
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="importheaders" :action="importUrl" :disabled="isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag style="margin-bottom: 15px">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip text-center" slot="tip">
            <!-- <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downloadModel">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showInportVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFileForm" :loading="isUploading">确 定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 账号校验结果 -->
    <el-dialog title="校验结果" :visible.sync="showCheckResult" width="430px" append-to-body>
      <div>
        <p>
          <b>未录入系统的订单：</b>
        </p>
        <div class="table_box table_box_new" style="margin-bottom: 15px;">
          <el-table :data="checkResultArr" border>
            <el-table-column label="行号" prop="rowNumber" width="80"> </el-table-column>
            <el-table-column label="账号" prop="accountNumber"> </el-table-column>
            <el-table-column label="三方单号" prop="otherNo"  />
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showCheckResult = false" >关 闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- <backOrderAfterListDialog ref="backOrderAfterListDialog"></backOrderAfterListDialog> -->
  </div>
</template>

<script>
import orderDetailDialog from "../components/orderDetailDialog.vue";
import editPriceDialog from "../components/editPrice.vue";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import gameListApi from "@/api/gameConfig/gameList";
import { getDicts } from "@/api/system/dict/data";
import selectBaopei from "../components/selectBaopei.vue";
import Cookies from "js-cookie";
import openWindownFn from "@/utils/openUrlByWindow.js";
import backOrderItem from "../components/backOrderItem.vue";
import shenQingDakuanDialog from "../components/shenQingDakuanDialog.vue";
import baopeiEditDialog from "../components/baopeiInfo.vue";
import shenQingShouhouDialog from "../components/shenQingShouhouDialog.vue";
import addGoodsDialog from "../../goodsList/addAndEdit.vue";
import authDialog from "@/views/tenantPages/shopManage/shopCenter/authDialog";

// 合同信息
import viewContract from "../../../aiqian/viewContract.vue";
// 创建合同
import createContract from "../../../aiqian/createContract.vue";

// 回收订单
import createOrderCustom from "./createOrderCustom.vue";

// 完成订单确认窗口
import finishOrderDialog from "../components/finishOrderDialog.vue";

import billDetail from "../../financialManage/billDetailDialog.vue";
// import backOrderAfterListDialog from "./backOrderAfterListDialog.vue";
import { backOrderHeaderList } from "../../../../utils/tableHeaders";

import editTableHeader from "../../../../components/common/editTableHeader.vue";

import { getUserListHeaderByType } from "../../../../api/tableHeader";
import supplyConfigApi from "@/api/system/supplyConfig";
import otherChannels from "@/api/retrieveManage/otherChannels";
import { listDept } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
export default {
  name: "RecycleOrdersmyBuy",
  components: {
    backOrderItem,
    orderDetailDialog,
    editPriceDialog,
    selectBaopei,
    shenQingDakuanDialog,
    baopeiEditDialog,
    shenQingShouhouDialog,
    addGoodsDialog,
    authDialog,
    viewContract,
    createOrderCustom,
    finishOrderDialog,

    billDetail,
    // backOrderAfterListDialog,
    editTableHeader,
    createContract,
  },
  data() {
    return {
      showCheckResult:false,
      checkResultArr:[],
      showInportVisible:false,
      isUploading:false,
      importheaders: {
        Authorization: "Bearer " + getToken(),
        timeout: 1000 * 60 * 10,
      },
      importUrl: process.env.VUE_APP_BASE_API + "/backClueOrder/checkGoods",

      columnList: [],
      statesMap: {
        0: {
          label: "全部",
          type: "",
        },
        1: {
          label: "交易中",
          type: "",
        },
        // 2: {
        //   label: "待审核",
        //   type: "warning",
        // },
        // 3: {
        //   label: "已审核",
        //   type: "success",
        // },
        4: {
          label: "交易完成",
          type: "success",
        },
        5: {
          label: "交易失败",
          type: "danger",
        },
      },
      loading: false,
      tableData: {
        records: [],
        total: 0,
      },
      actived: "0",
      gameList: [],
      timer: [],
      successTimer: [],
      errorTimer: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountNumber: "",
        dataType: "buy",
        createTimeStart: "",
        createTimeEnd: "",
        gameId: "",
        no: "",
        orderStatus: "",
        orderType: "",
        buyerPayStatus: "",
        changeBindState: "",
        sellerPhone: "",
        otherNo: "",
        buyerId: "",
        channel: "",
        deptIdList: [],
        buyerIdList:[],
        buyerTenantId:''
      },
      currentData: {},
      IMhost: "",
      exportloading: false,
      totalNumber: null,
      yuangongList: [],
      qudaoList: [],
      allDepts: [],
    };
  },
  created() {
    if (this.$route.query.orderStatus) {
      this.actived = this.$route.query.orderStatus;
      this.queryParams = { ...this.queryParams, ...this.$route.query };
      if(this.$route.query.deptIdList){
        this.queryParams.deptIdList = JSON.parse(this.queryParams.deptIdList)
      }
      if(this.queryParams.finishTimeStart&&this.queryParams.finishTimeEnd){
        this.successTimer = [this.queryParams.finishTimeStart,this.queryParams.finishTimeEnd]
      }
      if(this.queryParams.gameId){
        this.queryParams.gameId= Number(this.queryParams.gameId)
      }
      if(this.queryParams.buyerId){
        this.queryParams.buyerIdList= [Number(this.queryParams.buyerId)]
        this.queryParams.buyerId = ''
      }
    }
    this.getList();
    this.getTableHeader();
    this.getGameList();
    // this.getHost();
    this.getYuangongList();
    this.getQudaoList();
    this.getDeptList();
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    getRowBaopeiInfo() {
      return (str) => {
        if (str) {
          const obj = JSON.parse(str);
          let s = `${obj.collectionUserName} ${obj.collectionAccountName}  ${obj.collectionAccount} `;
          return s;
        }
      };
    },
    getRowsellerBankInfo() {
      return (str) => {
        if (str) {
          const obj = JSON.parse(str);
          obj.zhizhao = false;
          if (/[a-zA-Z]/.test(obj.idCard)) {
            obj.zhizhao = true;
          }
          // let s = `${obj.collectionRemark} `;
          return obj;
        }
      };
    },
    allYouzhiMap() {
      return this.$store.getters.allYouzhiMap;
    },
    formatter() {
      return (val) => {
        let formatter = new Intl.NumberFormat("en-US");
        const formattedNumber = formatter.format(val);
        return formattedNumber;
      };
    },
    retailDomain() {
      return this.$store.getters.retailDomain;
    },
  },
  activated() {
    // if (this.$router.currentRoute.query.orderStatus) {
    //   this.actived = this.$router.currentRoute.query.orderStatus;
    //   this.queryParams.orderStatus =
    //     this.$router.currentRoute.query.orderStatus;
    // }
    // this.getList();
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.showInportVisible = false;
      this.isUploading = false;
      this.$refs.upload.clearFiles();
      if(response.data&&response.data.length){
        // 
        this.checkResultArr = response.data
        this.showCheckResult = true
      }else{
        this.$alert("未发现系统内不存在的订单！", "校验结果");
      }
      
    },
    // 导出模版
    downloadModel() {
      this.isUploading = true;
        onSelfApi
          .backClueOrderexportCheckModel()
          .then((res) => {
            this.isUploading = false;
            // this.$download.name(res.msg);
            this.$download.downloadFile(res, "订单校验模板");
          })
          .catch((err) => {
            this.isUploading = false;
          });
    },
    openOrderCheck(){
      this.importUrl= process.env.VUE_APP_BASE_API + "/backClueOrder/checkGoods"
      this.showInportVisible = true;
    },

   
    // 查询部门列表
    async getDeptList() {
      try {
        if (this.checkPermi(["goods:list:deptSearch"])) {
          const { data } = await listDept();
          // console.log("%c Line:775 🌽 data", "color:#93c0a4", data);
          this.allDepts = data.filter((r) => r.parentId != 100);
        }
      } catch (error) {}
    },
    // // 获取自定义的三方渠道列表
    getQudaoList() {
      otherChannels
        .getQudaoList({
          isPage: 2,
          type: 2,
        })
        .then((response) => {
          this.qudaoList = response.rows;
        });
    },
    // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },
    // 打开表头设置
    headerSet() {
      this.$refs.editTableHeader.open(3);
    },
    // 查询表头
    getTableHeader() {
      getUserListHeaderByType({ type: 3 }).then((res) => {
        if (res.data && res.data.settingsJson) {
          this.columnList = JSON.parse(res.data.settingsJson);
        } else {
          this.columnList = [...backOrderHeaderList];
        }
      });
    },
    // headerSave
    headerSave(listJson) {
      this.columnList = [];
      this.$nextTick(() => {
        this.columnList = JSON.parse(listJson);
        this.$nextTick(() => {
          this.$refs.tableRef.doLayout();
        });
      });
      // this.getTableHeader();
    },

    openBillDialog(id, flag) {
      if (flag) {
        if (!id) {
          return this.$message.error("暂未生成账单！");
        }
        this.$refs.billDetail.open(id);
      }
    },
    clickHetong() {
      if (this.orderItem.orderType == 3) {
        this.$message.error("自建订单请在“合同管理”中自行签署合同！");
      }
    },
    openAfterOrder(orderItem) {
      // this.$refs.backOrderAfterListDialog.open(
      //   orderItem.id,
      //   orderItem.userType
      // );
    },

    // 查询选号网的域名
    // getData() {
    //   this.getDicts("retailDomain").then((r) => {
    //     // //console.log("%c Line:587 🍞 r", "color:#e41a6a", r);
    //     if (r.data && r.data.length) {
    //       this.retailDomain = this.arrayToObject(r.data, "dictLabel");
    //     }
    //   });
    // },
    // 打开创建回收单弹窗
    openCreate() {
      this.$refs.createOrderCustom.open();
    },
    // 修改自建订单
    // 打开编辑弹窗 完成或者取消
    editOrder(id, status, type) {
      // this.$refs.addDialog.open(row, status, type);
      this.$refs.createOrderCustom.open("edit", id);
    },
    // 获取包赔资料填报链接
    getBaopeiInfoLink(id) {
      onSelfApi.backClueOrdercreateKey({ id }).then((res) => {
        if (res.code == 200) {
          const baopeiLink = `${this.retailDomain["h5"].dictValue}pages/huishou/baopeiInfoCommit?hsKey=${res.msg}`;
          this.$copyText(baopeiLink).then((r) => {
            this.$message.success("包赔填报链接已复制到剪切板，60分钟内有效！");
          });
        }
      });
    },

    // 获取订单列表
    getList() {
      this.loading = true;
      if (this.timer && this.timer.length) {
        this.queryParams.createTimeStart = this.timer[0];
        this.queryParams.createTimeEnd = this.timer[1] + " " + "23:59:59";
      } else {
        this.queryParams.createTimeStart = "";
        this.queryParams.createTimeEnd = "";
      }
      if (this.successTimer && this.successTimer.length) {
        this.queryParams.finishTimeStart = this.successTimer[0];
        this.queryParams.finishTimeEnd =this.successTimer[1].length>10?this.successTimer[1]:
          (this.successTimer[1] + " " + "23:59:59");
      } else {
        this.queryParams.finishTimeStart = "";
        this.queryParams.finishTimeEnd = "";
      }
      this.totalNumber = null;
      onSelfApi.getbackClueOrderList(this.queryParams).then((response) => {
        this.tableData.records = [];
        this.tableData.records = response.rows;
        this.tableData.total = response.total;
        this.loading = false;
        if (response.params) {
          this.totalNumber = response.params;
        }
      });
    },

    // tabs切换时触发
    tabChange(e) {
      console.log("%c Line:452 🍆 e", "color:#4fff4B", e);
      // this.tableData.records = [];
      this.queryParams.orderStatus = e;
      if (e == 0) {
        this.queryParams.orderStatus = "";
      }
      this.$nextTick(() => {
        this.search();
      });
    },
    // 立即发布商品到商品管理
    fabuNow(id) {
      const obj = {};
      onSelfApi.getGoodsContent({ id }).then((res) => {
        obj.backOrderId = res.data.id;
        obj.goodsContent = res.data.goodsContent;
        this.$refs.addGoodsDialog.open("backOrder", obj);
      });
    },
    // 编辑商品
    editGoods(goodsId) {
      this.$refs.addGoodsDialog.open("view", goodsId);
    },
    // 编辑包赔资料弹窗
    openEditBaopeiInfo(row) {
      let flag = "edit";
      if (row.guaranteeTenantId) {
        flag = "view";
      }
      this.$refs.baopeiEditDialog.open(row, flag);
    },
    // 打款申请
    openDaKuan(row) {
      // 打开申请打款弹窗
      this.$refs.shenQingDakuanDialog.open(row, 1);
    },
    // 完成换绑
    wanchenghuanbang(row) {
      this.$confirm("完成之前请确认是否已经换绑,确定完成换绑吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.changeBindState({ id: row.id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    finishOrder(row) {
      if (row.guaranteeRefundStatus == 3) {
        return this.$message({
          type: "error",
          message: "订单有退款正在进行中，不能完成交易！",
        });
      }
      //弹出确认完成交易的弹窗
      this.$refs.finishOrderDialog.open(row.id);
    },
    // 打开售后提交弹窗
    openShouhou(row) {
      this.$refs.shenQingShouhouDialog.open(row);
    },
    // 删除订单
    delOrder(id) {
      this.$confirm(
        "删除后将无法查看且无法恢复，确定要删除该订单吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          onSelfApi.backClueOrderDelSelf({ id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 取消订单
    cancelOrder(row) {
      this.$prompt(
        "如果已支付，取消订单后请自行处理款项！请输入取消订单备注",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(({ value }) => {
          let obj = {
            id: row.id,
            remark: row.remark + "\n取消订单备注：" + value,
          };
          onSelfApi.backClueOrderCancelOrder(obj).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});

      // this.$confirm(
      //   "如果已支付，取消订单后请自行处理款项，确定取消该订单吗？",
      //   "提示",
      //   {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   }
      // )
      //   .then(() => {
      //     onSelfApi.backClueOrderCancelOrder({ id }).then((res) => {
      //       this.$message.success(res.msg);
      //       this.getList();
      //     });
      //   })
      //   .catch(() => {});
    },
    // 解散群组
    cancelGroupIM(id) {
      this.$confirm("此操作将解散该订单的聊天群组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.cancelGroup({ id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 恢复群组
    recoveryGroup(id) {
      onSelfApi.recoveryGroup({ id }).then((res) => {
        this.$message.success(res.msg);
        this.getList();
      });
    },

    // 查看详情
    viewInfo(row) {
      this.$refs.previewBackInfo.open(row.backId);
    },
    // 游戏列表
    getGameList() {
      gameListApi.getGameList().then((res) => {
        this.gameList = res.rows;
      });
    },
    // 获取IM域名
    getIMhost() {
      getDicts("IMhost").then((res) => {
        if (res.code == 200) {
          this.IMhost = res.data[0]?.dictValue;
        }
      });
    },
    // 签署合同
    createContract(row) {
      if(row.orderType==3){
        // 自建订单  只能发起自定义合同
        // 拉起创建合同弹窗
        return this.openAddHetong(row)
      }
      this.$confirm("请选择签署合同的方式：", "签署合同", {
        distinguishCancelAndClose: true,
        confirmButtonText: "系统生成合同",
        cancelButtonText: "自定义合同",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          onSelfApi
            .createContract({ id: row.id })
            .then((res) => {
              // console.log("%c Line:341 🍪 res", "color:#b03734", res);
              this.loading = false;
              if (res.code == 200) {
                this.getList();
                if (res.data.id) {
                  this.openContract(res.data.id)
                  // window.open(res.data.jfUrl);
                }
              } else if (res.code == 20012) {
                this.$confirm("店铺还未进行实名认证，是否立即认证？", "提示", {
                  confirmButtonText: "立即认证",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    // this.$router.push("/shopManageByTenant/shopCenter");
                    this.$refs.authDialog.open();
                  })
                  .catch((err) => {});
              }
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch((action ) => {
          if(action=='cancel'){
            // 拉起创建合同弹窗
            this.openAddHetong(row)
          }
        });
    },
    // 打开创建合同的弹窗
    openAddHetong(row) {
      this.$refs.createContractRef.open(row,2);
    },
    // 查看合同
    openContract(id) {
      this.$refs.viewContract.open(id);
      // onSelfApi.getContractUrl(row.signContractId).then((res) => {
      //   if (res.data.purchaserUrl) {
      //     window.open(res.data.purchaserUrl);
      //   }
      //   // if (res.data.purchaserUrl) {
      //   //   window.open(res.data.purchaserUrl);
      //   // }
      // });
    },
 
    // 跳转客服系统
    goIM(toGroup) {
      if (toGroup) {
        let obj = {
          type: "goChat",
          hxusername: toGroup,
          chatType: 'groupChat',
        };
        // 告诉IM系统，需要跳转聊天页
        this.$store.dispatch("postMsgToIM", obj);
      } else {
        this.$message.error("该订单没有群聊！");
      }
    },

    // 搜索
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 打开订单详情
    openOrderDetail(row) {
      this.$refs.orderDetailDialog.open(row.id);
    },
    // 改价
    gaijia(row) {
      this.$refs.editPriceDialog.open(row, "buyer");
    },
    // 一键拉群  卖家  回收商  于都客服
    groupChats(row) {
      this.$confirm("卖家和回收商确认交易该账号后再拉群, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.createGroupRoom(row).then((res) => {
            if (res.code == 200) {
              this.$alert(res.data.message);
            } else {
              this.$alert(res.msg);
            }
            this.getList();
          });
        })
        .catch(() => {});
    },

    // 拉包赔进群  打开选择包赔
    pullBaopei(row) {
      // 打开包赔商选择框
      this.currentData = row;
      this.$refs.selectBaopei.open();
    },
    // 确认拉包赔进群
    pullBaopeiSure(cpsId) {
      let params = {
        id: this.currentData.id,
        guaranteeId: cpsId,
      };
      onSelfApi.pullBaopeiGroup(params).then((res) => {
        if (res.code == 200) {
          this.$alert(res.msg);
        } else {
          this.$alert(res.msg);
        }
        this.getList();
      });
    },

    // 打开查看弹窗
    viewPhone(row) {
      this.$refs.viewPhone.open(row);
    },
    //重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.timer = [];
      this.successTimer = [];
      this.errorTimer = [];
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.table_box {
  padding: 0 !important;
  box-shadow: none !important;
}
.popover-box{
  max-width: 800px;max-height: 400px;overflow-y: auto;
  white-space: pre-wrap;
}
</style>